//
//  OSCTweetComposeViewController.m
//  OSChina
//
//  Created by 8b410-2 on 17/1/9.
//  Copyright © 2017年 abb. All rights reserved.
//

#import <TZImagePickerController/TZImagePickerController.h>
#import "PYPhotoBrowser.h"
#import "OSCTweetComposeViewController.h"
#import "GACompressionPicHandle.h"
#import "PlaceholderTextView.h"
#import "OSCEmoticonViewController.h"
#import "OSCTweetComposeViewModel.h"
#import "UITextView+RACAttribute.h"
#import "UITextView+OSCEmoticon.h"


@interface OSCTweetComposeViewController () <PYPhotosViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate,UITextViewDelegate>
/// 动弹发布viewModel
@property (nonatomic, strong) OSCTweetComposeViewModel *viewModel;
/// 动弹输入框
@property (nonatomic, strong) PlaceholderTextView *textView;
/// 图片浏览器
@property (nonatomic, strong) PYPhotosView *photosView;
/// 表情控制器
@property (nonatomic, strong) OSCEmoticonViewController *emoticonVC;
/// 工具栏
@property (nonatomic, strong) UIToolbar *toolbar;
/// 图片源选择提示
@property (nonatomic, strong) UIAlertController *addImageAlert;
/// 图片选择器(处理相机)
@property (nonatomic, strong) UIImagePickerController *imagePickerController;
/// 字数提醒item
@property (nonatomic, strong)  UIBarButtonItem *tipButtomItem;

@end

@implementation OSCTweetComposeViewController

@dynamic viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupNav];

}

- (void)bindViewModel {
    [super bindViewModel];
    
    RAC(self.navigationItem.rightBarButtonItem,enabled) = self.viewModel.enableSendSignal;
    
    [[[NSNotificationCenter defaultCenter]
      rac_addObserverForName:UIKeyboardWillChangeFrameNotification
      object:nil]
      subscribeNext:^(id x) {
          [self keyboardWillChangeFrame:x];
      }];
    
    [[RACObserve(self.viewModel, images) skip:1]
     subscribeNext:^(NSArray *imageArr) {
         [self.photosView reloadDataWithImages:[imageArr mutableCopy]];
     }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (!_photosView) {
        [self.textView becomeFirstResponder];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.textView resignFirstResponder];
}

- (void)setupUI {
    [self.view addSubview:self.textView];
    [self.view addSubview:self.toolbar];
    
    [self.toolbar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
    }];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.toolbar.mas_top);
    }];
}

- (void)setupNav {
    // 左边按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    // 右边按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(send)];
}

- (void)send {
    [self.viewModel.requestSendCommand execute:nil];
}

- (void)dismiss {
    [self.viewModel dismiss];
}

- (void)switchInputView {
    [self.textView resignFirstResponder];
    self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil;
    [self.textView becomeFirstResponder];
}

- (void)addImage {
    [self.textView resignFirstResponder];
    [self presentViewController:self.addImageAlert animated:YES completion:nil];
}

- (void)presentAlbumPrickerController {
    TZImagePickerController * albumPrickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:self.viewModel.maxImagesCount delegate:self];
    albumPrickerController.allowPickingOriginalPhoto = NO;
    albumPrickerController.allowPickingVideo = NO;
    albumPrickerController.navigationBar.barTintColor = [UIColor navigationbarColor];
    [self presentViewController:albumPrickerController animated:YES completion:nil];
}

- (void)keyboardWillChangeFrame:(NSNotification *)notify {
    
    NSValue *value = [notify.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect rect = [value CGRectValue];
    
    NSNumber *duration = [notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    
    NSNumber *curve = [notify.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    CGFloat bottomOffset = -(kScreen_Height - rect.origin.y);
    [self.toolbar mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(bottomOffset);
    }];
    
    [UIView animateWithDuration:[duration doubleValue] animations:^{
        [UIView setAnimationCurve:[curve integerValue]];
        [self.view layoutIfNeeded];
    }];
    
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    [self.viewModel hanglePickerImageFromCamera:image];
}

#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker
       didFinishPickingPhotos:(NSArray<UIImage *> *)photos
                 sourceAssets:(NSArray *)assets
        isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
                        infos:(NSArray<NSDictionary *> *)infos {
    [self.viewModel handlePickerImagesFromAlbum:photos];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - PYPhotosViewDelegate 

- (void)photosView:(PYPhotosView *)photosView didAddImageClickedWithImages:(NSMutableArray *)images {
    [self presentAlbumPrickerController];
}

#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if ([text isEqualToString: @"\n"]) {
        [self send];
        [textView resignFirstResponder];
        return NO;
    }
    
    if ([text isEqualToString: @"@"]) {
        // TODO: - at控制器
        return NO;
    }
    
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView {

    [self.viewModel setValue:[textView stringFromEmoticonAttributedWithType:OSCEmoticonStringTypeImageName] forKey:NSStringFromSelector(@selector(content))];
    
    // 输入文字数
    NSInteger count = [textView stringFromEmoticonAttributedWithType:OSCEmoticonStringTypeImageName].length;
    // 计算剩余字数
    NSInteger res = maxStrLength - count;
    // 修改剩余数
    [self.tipButtomItem setTitle:[NSString stringWithFormat:@"%ld/%d",res,maxStrLength]];
    // 修改item颜色
    UIColor *tipTextColor = res > 0 ? [UIColor grayColor] : [UIColor redColor];
    [self.tipButtomItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:tipTextColor, NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
    
}

#pragma mark - 懒加载

- (PlaceholderTextView *)textView {
    if (!_textView) {
        _textView = [[PlaceholderTextView alloc] init];
        _textView.placeholder = @"今天你动弹了吗？";
        [_textView setFont:[UIFont systemFontOfSize:15]];
        _textView.alwaysBounceVertical = YES;
        _textView.delegate = self;
        _textView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    }
    return _textView;
}

- (PYPhotosView *)photosView {
    if (!_photosView) {
        _photosView = [PYPhotosView photosView];
        _photosView.delegate = self;
        NSInteger photoViewPadding = 20;
        NSInteger photoMargin = 10;
        NSInteger photoViewWidht = (kScreenWidth - photoViewPadding * 2 - photoMargin * 2) / 3;
        _photosView.photoWidth = photoViewWidht;
        _photosView.photoHeight = photoViewWidht;
        _photosView.photoMargin = photoMargin;
        [self.view insertSubview:_photosView belowSubview:self.toolbar];
        [_photosView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view).offset(-(44 + photoViewPadding));
            make.right.equalTo(self.view).offset(-photoViewPadding);
            make.left.equalTo(self.view).offset(photoViewPadding);
            make.height.equalTo(_photosView.mas_width);
        }];
        [self.textView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.view);
            make.bottom.equalTo(_photosView.mas_top).offset(-photoViewPadding);
        }];
    }
    return _photosView;
}

- (OSCEmoticonViewController *)emoticonVC {
    if (!_emoticonVC) {
        _emoticonVC = [[OSCEmoticonViewController alloc] init];
        [_emoticonVC didSelectEmoticonBlock:^(OSCEmoticon *emoticon) {
            if (self.textView.text.length < maxStrLength && self.textView.attributedText.length < maxStrLength) {
                [self.textView insertEmoticon:emoticon font:self.textView.font];
            }
        }];
    }
    return _emoticonVC;
}

- (UIBarButtonItem *)tipButtomItem {
    if (!_tipButtomItem) {
        _tipButtomItem = [[UIBarButtonItem alloc]
                          initWithTitle:[NSString stringWithFormat:@"%d/%d",maxStrLength,maxStrLength]
                          style:UIBarButtonItemStylePlain
                          target:self action:nil];
        _tipButtomItem.enabled = NO;
    }
    return _tipButtomItem;
}

- (UIToolbar *)toolbar {
    if (!_toolbar) {
        _toolbar = [[UIToolbar alloc] init];
        UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
        fixedSpace.width = 25.0f;
        NSMutableArray *barButtonItems = [[NSMutableArray alloc] initWithObjects:fixedSpace, nil];
        NSArray *iconName = @[@"toolbar-image", @"toolbar-mention", @"toolbar-reference", @"toolbar-emoji"];
        NSArray *action   = @[@"addImage", @"", @"", @"switchInputView"];
        for (NSInteger i = 0; i < iconName.count; i++) {
            UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]
                                              initWithImage:[[UIImage imageNamed:iconName[i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
                                              style:UIBarButtonItemStylePlain
                                              target:self
                                              action:NSSelectorFromString(action[i])];
            barButtonItem.tintColor = [UIColor clearColor];
            [barButtonItems addObject:barButtonItem];
            [barButtonItems addObject:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil]];
        }
        [barButtonItems addObject:self.tipButtomItem];
        [barButtonItems addObject:fixedSpace];
        _toolbar.barTintColor = [UIColor colorWithRed:246.0/255 green:246.0/255 blue:246.0/255 alpha:1.0];
        _toolbar.items = barButtonItems;
    }
    return _toolbar;
}

- (UIAlertController *)addImageAlert {
    if (!_addImageAlert) {
        _addImageAlert = [UIAlertController alertControllerWithTitle:@"请选择操作" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
        @weakify(self);
        UIAlertAction *chooseFromPhotoAlbum = [UIAlertAction actionWithTitle:@"从相册选择" style:0 handler:^(UIAlertAction * _Nonnull action) {
            @strongify(self);
            [self presentAlbumPrickerController];
        }];
        UIAlertAction *chooseFromCamera = [UIAlertAction actionWithTitle:@"拍照" style:0 handler:^(UIAlertAction * _Nonnull action) {
            @strongify(self);
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                [self.imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];
                [self presentViewController:self.imagePickerController animated:YES completion:nil];
            } else {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"Device has no camera" preferredStyle:UIAlertControllerStyleAlert];
                
                [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    return;
                }]];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
        UIAlertAction *canecelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [_addImageAlert addAction:chooseFromCamera];
        [_addImageAlert addAction:chooseFromPhotoAlbum];
        [_addImageAlert addAction:canecelAction];
    }
    return _addImageAlert;
}

- (UIImagePickerController *)imagePickerController {
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
    }
    return _imagePickerController;
}

@end
